<template>
  <el-row :gutter="20" class="app-container">
    <Splitpanes>
      <pane size="16" v-if="$auth.hasRoleOr(['admin','manager','fishingceo'])">
        <el-col>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
      </pane>
      <pane :size="$auth.hasRoleOr(['admin','manager','fishingceo']) ? 84 : 100">
        <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="鱼塘" prop="pondId">
        <pond-select v-model="queryParams.pondId" placeholder="请选择鱼塘" />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in pond_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型" prop="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择类型" clearable>
          <el-option
            v-for="dict in pond_order_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pond:order:createDirect']"
        >直接创建订单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pond:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['pond:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderNo" width="140" />
      <el-table-column label="用户姓名" align="center" prop="userName" width="100" />
      <el-table-column label="手机号" align="center" prop="userPhone" width="120" />
      <el-table-column label="鱼塘" align="center" prop="pondName" width="100" />
      <el-table-column label="钓位" align="center" prop="seatCode" width="80" />
      <el-table-column label="订单类型" align="center" prop="orderTypeDesc" width="100" />
      <el-table-column label="订单状态" align="center" prop="statusDesc" width="100" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="center" prop="totalAmount" width="100">
        <template #default="scope">
          <span>¥{{ scope.row.totalAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已支付" align="center" prop="paidAmount" width="100">
        <template #default="scope">
          <span>¥{{ scope.row.paidAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['pond:order:edit']">修改</el-button>
          <el-button 
            v-if="scope.row.orderStatus == 1"
            link 
            type="success" 
            icon="Check" 
            @click="handleSettle(scope.row)" 
            v-hasPermi="['pond:order:settle']"
          >结算</el-button>
          <el-button 
            v-if="scope.row.orderStatus == 1"
            link 
            type="warning" 
            icon="Close" 
            @click="handleCancel(scope.row)" 
            v-hasPermi="['pond:order:cancel']"
          >取消</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pond:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改钓场订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" disabled />
        </el-form-item>
        <el-form-item label="所属钓场" prop="deptId">
          <dept-select 
            v-model="form.deptId" 
            @change="handleDeptChange"
          />
        </el-form-item>
        <el-form-item label="鱼塘" prop="pondId">
          <pond-select v-model="form.pondId" :dept-id="form.deptId" @change="handlePondChange" />
        </el-form-item>
        <el-form-item label="钓位" prop="seatId">
          <el-select v-model="form.seatId" placeholder="请选择钓位" clearable>
            <el-option 
              v-for="seat in availableSeats" 
              :key="seat.id" 
              :label="seat.code" 
              :value="seat.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-radio-group v-model="form.userType" @change="handleUserTypeChange">
            <el-radio label="new">散客（新用户）</el-radio>
            <el-radio label="existing">老客户</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 散客信息填写 -->
        <template v-if="form.userType === 'new'">
          <el-form-item label="手机号" prop="userPhone">
            <el-input v-model="form.userPhone" placeholder="请输入手机号（系统将自动创建用户）" />
          </el-form-item>
          <el-form-item label="用户姓名" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入用户姓名（可选）" />
          </el-form-item>
        </template>
        
        <!-- 老客户选择 -->
        <template v-if="form.userType === 'existing'">
          <el-form-item label="选择用户" prop="userId">
            <el-select 
              v-model="form.userId" 
              placeholder="请选择用户" 
              filterable
              clearable
              @change="handleUserSelect"
              style="width: 100%"
            >
              <el-option 
                v-for="user in userList" 
                :key="user.userId" 
                :label="`${user.userName || user.nickName} (${user.phonenumber})`" 
                :value="user.userId" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户信息" v-if="selectedUser">
            <div class="user-info">
              <p><strong>姓名：</strong>{{ selectedUser.userName || selectedUser.nickName }}</p>
              <p><strong>手机号：</strong>{{ selectedUser.phonenumber }}</p>
              <p><strong>邮箱：</strong>{{ selectedUser.email || '未填写' }}</p>
            </div>
          </el-form-item>
        </template>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker 
            v-model="form.startTime" 
            type="datetime" 
            placeholder="选择开始时间" 
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 结算订单对话框 -->
    <el-dialog title="结算订单" v-model="settleOpen" width="500px" append-to-body>
      <el-form ref="settleRef" :model="settleForm" :rules="settleRules" label-width="80px">
        <el-form-item label="订单编号">
          <span>{{ settleForm.orderNo }}</span>
        </el-form-item>
        <el-form-item label="用户信息">
          <span>{{ settleForm.userName }} ({{ settleForm.userPhone }})</span>
        </el-form-item>
        <el-form-item label="总金额">
          <span>¥{{ settleForm.totalAmount }}</span>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker 
            v-model="settleForm.endTime" 
            type="datetime" 
            placeholder="选择结束时间" 
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="settleForm.remark" type="textarea" placeholder="请输入结算备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSettle">确认结算</el-button>
          <el-button @click="settleOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
        </div>
      </pane>
    </Splitpanes>
  </el-row>
</template>

<script setup name="Order">
import { 
  listOrder, getOrder, delOrder, addOrder, updateOrder, 
  createDirectOrder, settleOrder, cancelOrder, createFromAppointment,
  updateOrderStatus, completeOrder, addOrderItem, 
  updateItemPayStatus, generateOrderNo 
} from "@/api/pond/order";
import { listSeat } from "@/api/pond/seat";
import { listUser } from "@/api/system/user";
import PondSelect from "@/components/PondSelect";
import DeptSelect from "@/components/DeptSelect";
import { useDeptTree } from "@/utils/deptTreeUtils";
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';

const { proxy } = getCurrentInstance();
const { pond_order_status, pond_order_type } = proxy.useDict('pond_order_status', 'pond_order_type');

const orderList = ref([]);
const open = ref(false);
const settleOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const availableSeats = ref([]);
const userList = ref([]);
const selectedUser = ref(null);

// 使用钓场树形选择器
const {
  deptOptions,
  getDeptTree,
  handleSidebarDeptNodeClick,
  handleFormDeptNodeClick
} = useDeptTree();

const data = reactive({
  form: {
    userType: 'new' // 默认选择散客
  },
  settleForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    userName: null,
    userPhone: null,
    pondId: null,
    orderStatus: null,
    orderType: null,
    deptId: null,
  },
  rules: {
    deptId: [
      { required: true, message: "所属钓场不能为空", trigger: "change" }
    ],
    pondId: [
      { required: true, message: "鱼塘不能为空", trigger: "change" }
    ],
    seatId: [
      { required: true, message: "钓位不能为空", trigger: "change" }
    ],
    userType: [
      { required: true, message: "请选择用户类型", trigger: "change" }
    ],
    userId: [
      { required: true, message: "请选择用户", trigger: "change" }
    ],
    userName: [
      { required: false, message: "用户姓名不能为空", trigger: "blur" }
    ],
    userPhone: [
      { required: true, message: "手机号不能为空", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: "blur" }
    ],
    startTime: [
      { required: false, message: "开始时间不能为空", trigger: "change" }
    ]
  },
  settleRules: {
    endTime: [
      { required: true, message: "结束时间不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, settleForm, rules, settleRules } = toRefs(data);

/** 查询钓场订单列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != dateRange && '' != dateRange) {
    queryParams.value.params["beginTime"] = dateRange.value[0];
    queryParams.value.params["endTime"] = dateRange.value[1];
  }
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderNo: null,
    deptId: null,
    pondId: null,
    seatId: null,
    userType: 'new',
    userId: null,
    userName: null,
    userPhone: null,
    startTime: null,
    remark: null
  };
  availableSeats.value = [];
  userList.value = [];
  selectedUser.value = null;
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId || item.id);
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 生成订单编号
  generateOrderNo().then(response => {
    form.value.orderNo = response.data;
  });
  open.value = true;
  title.value = "添加钓场订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _orderId = row ? (row.orderId || row.id) : ids.value[0]
  getOrder(_orderId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改钓场订单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.orderId != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        createDirectOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("添加成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  let _orderIds;
  // 判断是否为单个删除：row存在且有id或orderId属性
  if (row && (row.id || row.orderId)) {
    // 单个删除
    _orderIds = row.orderId || row.id;
  } else {
    // 批量删除 - 过滤掉undefined值并用逗号连接
    const validIds = ids.value.filter(id => id !== undefined && id !== null && id !== '');
    
    if (validIds.length === 0) {
      proxy.$modal.msgError("请选择要删除的订单");
      return;
    }
    
    _orderIds = validIds.join(',');
  }
  
  const confirmText = (row && (row.id || row.orderId)) ? 
    `是否确认删除钓场订单编号为"${_orderIds}"的数据项？` : 
    `是否确认删除选中的${ids.value.length}条订单数据？`;
    
  proxy.$modal.confirm(confirmText).then(() => {
    return delOrder(_orderIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('pond/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

/** 结算订单 */
function handleSettle(row) {
  settleForm.value = {
    orderId: row.orderId || row.id,
    orderNo: row.orderNo,
    userName: row.userName,
    userPhone: row.userPhone,
    totalAmount: row.totalAmount,
    endTime: null,
    remark: null
  };
  settleOpen.value = true;
}

/** 提交结算 */
function submitSettle() {
  proxy.$refs["settleRef"].validate(valid => {
    if (valid) {
      settleOrder(settleForm.value).then(response => {
        proxy.$modal.msgSuccess("结算成功");
        settleOpen.value = false;
        getList();
      });
    }
  });
}

/** 左侧钓场树节点点击事件 */
function handleNodeClick(data) {
  handleSidebarDeptNodeClick(data, (deptId) => {
    queryParams.value.deptId = deptId;
    handleQuery();
  });
}

/** 钓场选择变化事件 */
function handleDeptChange(deptId) {
  form.value.pondId = null;
  form.value.seatId = null;
  availableSeats.value = [];
  console.log('选择的钓场ID:', deptId);
}

/** 重置搜索 */
function resetQuery() {
  dateRange.value = [];
  queryParams.value.deptId = null;
  proxy.$refs.deptTreeRef && proxy.$refs.deptTreeRef.setCurrentKey(null);
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 取消订单 */
function handleCancel(row) {
  proxy.$modal.prompt('请输入取消原因', '取消订单', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '取消原因不能为空'
  }).then(({ value }) => {
    cancelOrder(row.orderId || row.id, value).then(response => {
      proxy.$modal.msgSuccess("取消成功");
      getList();
    });
  }).catch(() => {});
}

/** 鱼塘变化时获取钓位列表 */
function handlePondChange(pondId) {
  form.value.seatId = null; // 清空已选择的钓位
  if (pondId) {
    // 调用获取钓位列表的API
    listSeat({ pondId: pondId, pageNum: 1, pageSize: 1000 }).then(response => {
      availableSeats.value = response.rows || [];
      console.log('获取到的钓位列表:', availableSeats.value);
    }).catch(error => {
      console.error('获取钓位列表失败:', error);
      availableSeats.value = [];
      proxy.$modal.msgError("获取钓位列表失败");
    });
  } else {
    availableSeats.value = [];
  }
}

/** 获取钓友用户列表 */
function getFishingUsers() {
  const params = {
    pageNum: 1,
    pageSize: 1000,
    roleId: 2, // 钓友角色ID
  };
  listUser(params).then((response) => {
    userList.value = response.rows || [];
  });
}

/** 用户类型切换 */
function handleUserTypeChange(userType) {
  // 清空用户相关字段
  form.value.userId = null;
  form.value.userName = null;
  form.value.userPhone = null;
  selectedUser.value = null;
  
  // 动态更新验证规则
  if (userType === 'new') {
    // 散客模式：手机号必填，用户名可选
    rules.value.userPhone[0].required = true;
    rules.value.userName[0].required = false;
    rules.value.userId[0].required = false;
    userList.value = [];
  } else {
    // 老客户模式：必须选择用户，加载用户列表
    rules.value.userId[0].required = true;
    rules.value.userPhone[0].required = false;
    rules.value.userName[0].required = false;
    getFishingUsers(); // 选择老客户时加载用户列表
  }
}


/** 选择用户 */
function handleUserSelect(userId) {
  const user = userList.value.find(u => u.userId === userId);
  if (user) {
    selectedUser.value = user;
    form.value.userName = user.userName || user.nickName;
    form.value.userPhone = user.phonenumber;
  } else {
    selectedUser.value = null;
  }
}

onMounted(() => {
  getList();
  getDeptTree(); // 获取部门树数据
});
</script>

<style scoped>
.user-info {
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.user-info p {
  margin: 4px 0;
  color: #606266;
}

.user-info strong {
  color: #303133;
}
</style>